import { useEffect, useState } from 'react';
import { useDispatch, useSearchParams, useSelector } from 'umi';

import { requestWithoutCache } from '@/utils/request';

import crowdInfoToReduxInfo from '../utils/crowdInfoToReduxInfo';
import reduxInfoToFilterData from '../utils/reduxInfoToFilterData';
import remoteFilterToFilterData from '../utils/remoteFilterToFilterData';
import { getSelectedTags } from '../utils/storage';

const getTagsFromFilter = (filter, tags = []) => {
  const isTag = (item) =>
    ['custom', 'tag', 'crowd', 'biz_tag'].includes(item.type);
  if (filter.type) {
    if (isTag(filter)) tags.push(filter);
    else {
      filter.filters?.forEach((filter) => getTagsFromFilter(filter, tags));
    }
  }
  return tags;
};

const useCrowdInfoToReduxInfo = () => {
  const [searchParams] = useSearchParams();
  const crowdId = searchParams.get('crowd_id');
  // const {
  //   query: { crowd_id: crowdId },
  // } = useLocation();
  const [result, setResult] = useState([]);
  const dispatch = useDispatch();

  const dims = useSelector((state) => state.label.dims);

  useEffect(() => {
    if (!dims || !crowdId) return;
    requestWithoutCache(`/api/dmp/crowd/list?id=${crowdId}`).then(
      async (res) => {
        const value = remoteFilterToFilterData(
          res.data[0].filter,
          reduxInfoToFilterData([]),
        );
        const filterItems = getTagsFromFilter(value);
        const resultData = await crowdInfoToReduxInfo(filterItems, dims);
        setResult(resultData);
        // todo
      },
    );
  }, [crowdId, dims]);

  useEffect(() => {
    if (!crowdId) {
      const selectedGroupTag = getSelectedTags() ?? [];
      setResult(selectedGroupTag);
    }
  }, [crowdId]);

  useEffect(() => {
    if (result.length > 0) {
      if (crowdId) {
        dispatch({
          type: 'label/saveCrowdSelectedGroupTags',
          payload: { crowdId, groupTags: result },
        });
      } else {
        dispatch({
          type: 'label/saveSelectedGroupTag',
          payload: result,
        });
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [result]);

  return result;
};

export default useCrowdInfoToReduxInfo;
